﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Dos.ORM;
using Model;

namespace Logic
{
    public class SaleFeeLogic
    {
        public static int Insert(TB_Sale_Fee saleFee)
        {
            if (!Exists(saleFee.FeeDate, saleFee.SaleAccount))
            {
                return DB.Context.Insert<TB_Sale_Fee>(saleFee);
            }
            else
            {
                if (ExistsSuc(saleFee.FeeDate, saleFee.SaleAccount))
                {//如果存在正常数据，则无操作
                    return 0;
                }
                else
                { //存在的相关数据为 0 ，则更新
                    return DB.Context.Update<TB_Sale_Fee>(saleFee, d => d.FeeDate == saleFee.FeeDate);
                }

            }
        }

        /// <summary>
        /// 存在成功获取到的酬金数据
        /// </summary>
        /// <param name="feeDate"></param>
        /// <returns></returns>
        public static bool ExistsSuc(string feeDate, string saleAccount)
        {
            bool exists = DB.Context.Exists<TB_Sale_Fee>(d => d.FeeDate == feeDate && d.FeeSucCount > 0 && d.SaleAccount == saleAccount);
            return exists;
        }

        /// <summary>
        /// 存在酬金数据
        /// </summary>
        /// <param name="feeDate"></param>
        /// <returns></returns>
        public static bool Exists(string feeDate, string saleAccount)
        {
            return DB.Context.Exists<TB_Sale_Fee>(d => d.FeeDate == feeDate && d.SaleAccount == saleAccount);
        }

        public static List<TB_Sale_Fee> GetFeeByMonth(string feeMonth)
        {
            return DB.Context.From<TB_Sale_Fee>().Where(d => d.FeeDate == feeMonth)
                .ToList();
            
        }

        public static int GetAllSucCount(string feeMonth)
        {
            object obj = DB.Context.FromSql("select sum(feesuccount) from tb_sale_fee where feedate='" + feeMonth + "'").ToScalar();
            if (obj == null || obj == DBNull.Value)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }

        public static int GetAllFailCount(string feeMonth)
        {
            object obj = DB.Context.FromSql("select sum(feefailcount) from tb_sale_fee where feedate='" + feeMonth + "'").ToScalar();
            if (obj == null || obj == DBNull.Value)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
    }
}
